package learn.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.text.MessageFormat;
import java.util.Arrays;

/**
 * 写（多个byteBuffer分散写，scattering）
 * 读（多个byteBuffer聚合读，gatthering）
 *  telnet 作为客户端连接，回车占2个字节
 * @USER white
 * @DATETIME 2020/10/17 8:08
 */
public class NioServerDemo {

    public static void main(String[] args) throws IOException {
        new NioServerDemo().start();
    }

    public void start() throws IOException {
        ServerSocketChannel channel = ServerSocketChannel.open();
        channel.bind(new InetSocketAddress(9901));
        SocketChannel client = channel.accept();

        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(3);
        byteBuffers[1] = ByteBuffer.allocate(5);

        while (true) {
            long readed = 0;
            while (readed < 8) {
                readed += client.read(byteBuffers);
                System.out.println("readed=====" + readed);
            }
            Arrays.asList(byteBuffers).stream().map(byteBuffer -> MessageFormat.format("position:{0}  mark:{1}  limit:{2}", byteBuffer.position(), byteBuffer.mark(), byteBuffer.limit()))
                    .forEach(System.out::println);
            Arrays.asList(byteBuffers).stream().forEach(byteBuffer -> {
                byteBuffer.flip();
            });
            System.out.println("flip=====================");
            Arrays.asList(byteBuffers).stream().map(byteBuffer -> MessageFormat.format("position:{0}  mark:{1}  limit:{2}", byteBuffer.position(), byteBuffer.mark(), byteBuffer.limit()))
                    .forEach(System.out::println);
            long writed=0;
            while (writed<8){
                writed +=client.write(byteBuffers);
            }
            Arrays.asList(byteBuffers).stream().forEach(byteBuffer -> {
                byteBuffer.clear();
            });
        }

    }

}
